<template>
  <div>
    <el-form
      :model="editCustomerData"
      v-loading="loading"
      label-position="left"
      size="small"
      :rules="rules"
      ref="approvalform"
      label-width="150px"
      class="project-form"
    >
      <el-form-item label="业务模式" prop="gua_type">
        <c-select
          placeholder="请选择业务模式"
          v-model="editCustomerData.gua_type"
          class="form-control-ml"
          :options="enumGuaType"
        ></c-select>
      </el-form-item>

      <el-form-item label="审批通道" prop="channel_type">
        <c-select
          :options="enumChannelType"
          placeholder="请选择审批通道"
          class="form-control-ml"
          v-model="editCustomerData.channel_type"
        ></c-select>
      </el-form-item>

      <el-form-item label="项目类型" prop="project_type">
        <c-select
          :options="enumProjectType"
          placeholder="请选择项目类型"
          class="form-control-ml"
          v-model="editCustomerData.project_type"
        ></c-select>
      </el-form-item>

      <el-form-item
        label="联保机构"
        prop="gua_service_id"
        v-if="isUnionType"
        :rules="{
          required: true,
          message: '请选择联保机构',
          trigger: 'change',
        }"
      >
        <select-org-credit
          v-model="editCustomerData.gua_service_id"
          @select="handleAccessAgencyChange"
          class="form-control-ml"
          placeholder="推荐担保机构"
        ></select-org-credit>
      </el-form-item>

      <el-form-item label="行业分类" prop="parent_main_business_code">
        <select-industrial-class
          filterable
          class="form-control-ml"
          v-model="editCustomerData.parent_main_business_code"
          @select="selectIndustrial"
          placeholder="请选择行业分类"
          @change="getIsMicroEnt"
        ></select-industrial-class>
      </el-form-item>

      <el-form-item label="是否为十二大产业" prop="is_ind12">
        <el-radio-group v-model="editCustomerData.is_ind12">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="十二大产业分类"
        prop="main_business"
        v-if="+editCustomerData.is_ind12 === 1"
      >
        <select-main-business
          class="form-control-ml"
          v-model="editCustomerData.main_business"
          placeholder="请选择十二大产业分类"
        ></select-main-business>
      </el-form-item>

      <el-form-item label="资产总额" prop="assets_funds">
        <el-input
          placeholder="资产总额"
          @change="getIsMicroEnt"
          v-input-number="{ min: 0, fixed: 2 }"
          v-model="editCustomerData.assets_funds"
          class="form-control-ml"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="营业收入" prop="sale_income">
        <el-input
          placeholder="营业收入"
          @change="getIsMicroEnt"
          v-input-number="{ min: 0, fixed: 2 }"
          v-model="editCustomerData.sale_income"
          class="form-control-ml"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="从业人数" prop="emp_temp_total">
        <el-input
          placeholder="从业人数"
          @change="getIsMicroEnt"
          v-input-number="{ min: 0, fixed: 0 }"
          v-model="editCustomerData.emp_temp_total"
          class="form-control-ml"
        >
          <span slot="append">人</span>
        </el-input>
      </el-form-item>

      <el-form-item label="是否中小微">
        <el-radio-group v-model="editCustomerData.is_micro_ent" :disabled="true">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="中小微类型" v-if="+editCustomerData.is_micro_ent === 1">
        <c-select
          :disabled="true"
          v-model="editCustomerData.micro_ent_type"
          :options="{
            1: '微型',
            2: '小型',
            3: '中型',
          }"
          placeholder="中小微类型"
          class="form-control-ml"
        ></c-select>
        <el-button size="small" type="info">
          <a
            :href="'https://attach.qedan.com/template/中小微企业划分标准.pdf' + `?${+new Date()}`"
            target="_blank"
            download="判断依据"
            class="text-white"
          >
            判断依据
          </a>
        </el-button>
      </el-form-item>

      <el-form-item label="项目负责人: A角" prop="res_a">
        <select-staff
          v-model="editCustomerData.res_a"
          ref="resA"
          class="form-control-ml"
          placeholder="请选择项目负责人: A角"
        ></select-staff>
      </el-form-item>
      <el-form-item label="项目负责人: B角" prop="res_b">
        <select-staff
          v-model="editCustomerData.res_b"
          ref="resB"
          class="form-control-ml"
          placeholder="请选择项目负责人: B角"
        ></select-staff>
      </el-form-item>
      <el-form-item label="项目风控员" prop="res_user_id_risk_point" v-if="isRisk">
        <select-staff
          v-model="editCustomerData.res_user_id_risk_point"
          ref="risk"
          class="form-control-ml"
          placeholder="请选择项目风控员"
        ></select-staff>
      </el-form-item>
      <el-form-item label="产品选择" prop="project_type_id">
        <select-credit-product
          placeholder="请选择担保产品（非必填）"
          class="form-control-ml"
          clearable
          v-model="editCustomerData.project_type_id"
          @change="setLoanMode"
          :project-type="editCustomerData.gua_type"
        ></select-credit-product>
      </el-form-item>

      <el-form-item label="指定银行">
        <select-org-bank
          v-model="editCustomerData.bank_id"
          :project-type="editCustomerData.gua_type"
          placeholder="选择指定银行（非必填）"
          @select="setPublicName"
          filterable
          clearable
          class="form-control-ml"
        ></select-org-bank>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="saveLoading" class="btn-long" @click="submitForm">
          受理
        </el-button>
        <el-button type="danger" :loading="saveLoading" class="btn-long" @click="handleRefuse">
          拒绝
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { enumChannelType, enumProjectType, enumGuaType } from '@/bigcredit/views/program/enum'
import SelectOrgCredit from '@/bigcredit/views/program/components/SelectCredit'
import SelectIndustrialClass from '@/credit/components/select/SelectIndustrialClass.vue'
import SelectMainBusiness from '@/credit/components/select/SelectMainBusiness.vue'
import SelectStaff from '@/components/select/SelectStaff'
import SelectCreditProduct from '@/bigcredit/components/select/SelectCreditProduct'
import SelectOrgBank from '@/bigcredit/views/program/components/SelectOrgBank'
import { mapGetters } from 'vuex'
export default {
  components: {
    SelectOrgCredit,
    SelectIndustrialClass,
    SelectMainBusiness,
    SelectStaff,
    SelectCreditProduct,
    SelectOrgBank,
  },
  props: {
    queryId: String,
  },
  data() {
    const isEqPersonValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (this.editCustomerData.res_b === this.editCustomerData.res_a) {
        callback(new Error('项目A角与项目B角不能为同一个人'))
      } else {
        callback()
      }
    }
    return {
      enumGuaType,
      enumChannelType,
      enumProjectType,
      loading: false,
      tableName: 'customer_related',
      editCustomerData: {
        gua_type: '',
        channel_type: '',
        project_type: '',
        parent_main_business_code: '',
        is_ind12: '',
        main_business: '',
        res_a: '',
        res_b: '',
        res_user_id_risk_point: '',
        project_type_id: '',
        gua_service_id: '',
        assets_funds: '',
        sale_income: '',
        emp_temp_total: '',
        is_micro_ent: '',
        micro_ent_type: '',
      },
      rules: {
        gua_type: { required: true, message: '请选择业务模式', trigger: 'change' },
        channel_type: { required: true, message: '请选择审批通道', trigger: 'change' },
        project_type: { required: true, message: '请选择项目类型', trigger: 'change' },
        parent_main_business_code: {
          required: true,
          message: '请选择行业分类',
          trigger: 'change',
        },
        is_ind12: { required: true, message: '请选择是否为十二大产业', trigger: 'change' },
        main_business: { required: true, message: '请选择十二大产业分类', trigger: 'change' },
        res_a: [
          { required: true, message: '请选择A角', trigger: 'change' },
          { validator: isEqPersonValidator, trigger: 'change' },
        ],
        res_b: [
          { required: true, message: '请选择B角', trigger: 'change' },
          { validator: isEqPersonValidator, trigger: 'change' },
        ],
        res_user_id_risk_point: { required: true, message: '请选择风控员', trigger: 'change' },

        assets_funds: { required: true, message: '请输入资产总额', trigger: 'blur' },
        sale_income: { required: true, message: '请输入销售收入', trigger: 'blur' },
        emp_temp_total: { required: true, message: '请输入从业人数', trigger: 'blur' },
      },
      tableData: {},
      saveLoading: false,
      isRisk: true,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'org']),
    // 是否需要选择联保机构
    isUnionType() {
      return +this.editCustomerData.gua_type === 4
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {
    this.getIsSelectRisk()
  },
  mounted() {},
  methods: {
    getIsMicroEnt() {
      if (
        !this.editCustomerData.parent_main_business_code ||
        !this.editCustomerData.sale_income ||
        !this.editCustomerData.assets_funds ||
        !this.editCustomerData.emp_temp_total
      ) {
        return
      }
      this.$api
        .getData(this.$serviceName, 'datum_customer_attachment/statistics/', {
          'apiKey.kv': 'query-sme',
          'ind_code.kv': this.editCustomerData.parent_main_business_code,
          'income.kv': this.editCustomerData.sale_income,
          'assert.kv': this.editCustomerData.assets_funds,
          'emp.kv': this.editCustomerData.emp_temp_total,
        })
        .then(res => {
          const data = res?.data ?? {}
          this.editCustomerData.is_micro_ent = data.is_micro_ent
          this.editCustomerData.micro_ent_type = data.micro_ent_type
        })
    },
    getIsSelectRisk() {
      this.$api
        .getData(this.$serviceName, 'workflow_risk_view', {
          'service_id.eq': this.clientId,
        })
        .then(res => {
          const data = res?.data ?? []
          this.isRisk = !!data.length
        })
    },
    submitForm() {
      this.$refs.approvalform.validate(valid => {
        if (valid) {
          this.submitData()
        } else {
          this.$message.warning('填写的数据有误，请检查填写内容')
        }
      })
    },
    submitData() {
      this.saveLoading = true
      const data = {
        gua_type: this.editCustomerData.gua_type,
        channel_type: this.editCustomerData.channel_type,
        project_type: this.editCustomerData.project_type,
        parent_main_business_code: this.editCustomerData.parent_main_business_code,
        parent_main_business: this.editCustomerData.parent_main_business,
        is_ind12: this.editCustomerData.is_ind12,
        main_business: this.editCustomerData.main_business,
        assets_funds: this.editCustomerData.assets_funds,
        sale_income: this.editCustomerData.sale_income,
        emp_temp_total: this.editCustomerData.emp_temp_total,
        is_micro_ent: this.editCustomerData.is_micro_ent,
        micro_ent_type: this.editCustomerData.micro_ent_type,
        res_a: this.editCustomerData.res_a,
        res_b: this.editCustomerData.res_b,
        res_a_name: (this.$refs.resA && this.$refs.resA.getSelectedName()) || '',
        res_b_name: (this.$refs.resB && this.$refs.resB.getSelectedName()) || '',
        res_user_id_risk_point: this.editCustomerData.res_user_id_risk_point,
        res_person_risk_point: (this.$refs.risk && this.$refs.risk.getSelectedName()) || '',
        gua_service_name: this.isUnionType ? this.editCustomerData.gua_service_name : '',
        gua_service_id: this.isUnionType ? this.editCustomerData.gua_service_id : '',
        project_type_id: this.editCustomerData.project_type_id || '',
        project_type_name: this.editCustomerData.project_type_name || '',
        bank_id: this.editCustomerData.bank_id || '',
        bank_name: this.editCustomerData.bank_name,
        bank_code: this.editCustomerData.bank_code,
        bank_type: this.editCustomerData.bank_type,
        is_approval: 1,
        approved_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        approval_person: this.user.realName,
        service_id: this.clientId,
      }
      this.$api
        .updateData(this.$serviceName, this.tableName, this.queryId, data)
        .then(() => {
          this.$emit('close', false)
          this.$emit('success', true)
          this.$message.success('受理成功')
        })
        .catch(err => {
          if (err) {
            const errStr =
              typeof err.data?.error_description === 'string'
                ? err.data?.error_description
                : '操作失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    handleRefuse() {
      if (!this.customerRelatedId) {
        return
      }
      this.$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入不通过原因' : true),
      })
        .then(({ value }) => {
          this.saveLoading = true
          this.$api
            .updateData(this.$serviceName, 'customer_related', this.customerRelatedId, {
              confuse_status: 3,
              confuse_time: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
              confuse_person: this.user.realName,
              confuse_des: value,
              is_approval: 2,
              approved_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
            })
            .then(() => {
              this.$emit('close', false)
              this.$emit('success', true)
              this.$message.success('项目已拒绝')
            })
            .catch(() => {
              this.$message.error(`项目拒绝失败，请重试`)
            })
            .finally(() => {
              this.saveLoading = false
            })
        })
        .catch(() => {})
    },
    setPublicName(bank) {
      this.editCustomerData.bank_type = bank.agency_type_sub || ''
      this.editCustomerData.bank_code = bank.agency_code || ''
      this.editCustomerData.bank_name = bank.agency_name || ''
    },
    setLoanMode(_, select) {
      this.editCustomerData.project_type_name = select.load_name || ''
    },
    selectIndustrial(v, l) {
      this.editCustomerData.parent_main_business = l?.ind_class_name ?? ''
    },
    handleAccessAgencyChange(agency) {
      this.editCustomerData.gua_service_name = agency?.agency_name || ''
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      this.$api
        .getDataFromId(this.$serviceName, this.tableName, this.queryId)
        .then(res => {
          this.tableData = res?.data ?? {}
          this.editCustomerData = {
            ...this.tableData,
            gua_type: +this.tableData.gua_type ? this.tableData.gua_type : '',
            is_ind12: this.tableData.is_ind12 || '0',
            is_micro_ent: this.tableData.is_micro_ent || '1',
          }
        })
        .finally(() => {
          this.$nextTick(() => {
            this.$refs.approvalform?.clearValidate()
          })
          this.loading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
